﻿(function ($) {
    var map;                 //地图对象
    var settings;            //可配置的字段
    var iMarker;             //自定义标注的点
    var autoMarkers = [];    //搜索得到的多个结果点
    $.fn.baidumap = function (options) {
        var defaults = {
            MapContainer: "mapContainer",    //地图容器ID
            GeoContainer: "txtGeoCode",      //显示最新标注点的坐标结果的容器ID
            CityName: "",                    //城市名称
            SearchAddress: "",               //搜索地址
            PointString: "",                 //以逗号分割表示的经纬度值
            ZoomNum: 15,                     //地图显示的放大级别
            IconPath: "/Images/baidu_blue.png"  //自定义标记点的图片路径
        };
        settings = $.extend(defaults, options);

        map = new BMap.Map(settings.MapContainer);
        map.addControl(new BMap.NavigationControl());
        map.addControl(new BMap.ScaleControl());
        map.addControl(new BMap.OverviewMapControl());
        map.addControl(new BMap.MapTypeControl());
        map.enableScrollWheelZoom(true);

        bindMapContextMenu();
        loadMap();
    };

    //显示地图
    //1、经纬度和地址都存在，则按照地址搜索标注点，同时，标注经纬度为自定义点
    //2、只有经纬度，则标注为自定义点
    //3、只有地址，按照地址查询，标注搜索点
    //4、如果经纬度和地址都没值，则显示城市地图
    //5、如果城市也没有值，则默认显示北京地图
    function loadMap() {
        if (settings.PointString && settings.SearchAddress) {
            var localSearch = new BMap.LocalSearch(settings.CityName, { renderOptions: { map: map, selectFirstResult: false, autoViewport: true } });
            localSearch.setSearchCompleteCallback(function (searchResult) {
                removeMarkers(map);
                if (localSearch.getStatus() == BMAP_STATUS_SUCCESS) {
                    var count = searchResult.getCurrentNumPois();
                    for (var i = 0; i < count ; i++) {
                        addMarker(searchResult.getPoi(i).point);
                    }
                    var point = new BMap.Point($.trim(settings.PointString.split(',')[0]), $.trim(settings.PointString.split(',')[1]));
                    addDragalbeMarker(point)
                    var pointArr = [];
                    pointArr = autoMarkers;
                    pointArr.push(iMarker);
                    map.getViewport(pointArr);
                }
            });
            localSearch.search(settings.CityName + " " + settings.SearchAddress);
        } else if (settings.PointString) {
            var lng = $.trim(settings.PointString.split(',')[0]);
            var lat = $.trim(settings.PointString.split(',')[1]);
            var point = new BMap.Point(lng, lat);
            removeIMarker();
            map.centerAndZoom(point, settings.ZoomNum);
            addDragalbeMarker(point);
        } else if (settings.SearchAddress) {
            var localSearch = new BMap.LocalSearch(settings.CityName, { renderOptions: { map: map, selectFirstResult: false, autoViewport: true } });
            localSearch.setSearchCompleteCallback(function (searchResult) {
                removeMarkers(map);
                if (localSearch.getStatus() == BMAP_STATUS_SUCCESS) {
                    var count = searchResult.getCurrentNumPois();
                    for (var i = 0; i < count ; i++) {
                        addMarker(searchResult.getPoi(i).point);
                    }
                    map.centerAndZoom(searchResult.getPoi(0).point, settings.ZoomNum);
                }
            });
            localSearch.search(settings.CityName + " " + settings.SearchAddress);
        }
        else if (settings.CityName) {
            var localSearch = new BMap.LocalSearch(map);
            localSearch.enableAutoViewport();
            localSearch.setSearchCompleteCallback(function (searchResult) {
                removeMarkers(map);
                if (localSearch.getStatus() == BMAP_STATUS_SUCCESS) {
                    map.centerAndZoom(searchResult.getPoi(0).point, 12);
                }
            });
            localSearch.search(settings.CityName);
        }
        else {
            map.centerAndZoom("北京");
        }
    }

    //绑定地图右键单击事件
    function bindMapContextMenu() {
        //右键菜单 
        var menu = new BMap.ContextMenu();
        //右键菜单项目  
        var txtMenuItem = [{
            text: '标注',
            callback: function (point) {
                removeIMarker(map);
                addDragalbeMarker(point);
            }
        }];
        for (var i = 0; i < txtMenuItem.length; i++) {
            //菜单添加项目
            menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
            //if (i == 1 || i == 3) {
            //    menu.addSeparator();  //添加右键菜单的分割线  
            //}
        }
        map.addContextMenu(menu);
    }

    //绑定信息框
    function bindInfoWindow(marker, point) {
        marker.addEventListener("click", function (e) {
            var geoc = new BMap.Geocoder();
            geoc.getLocation(point, function (rs) {
                var addComp = rs.addressComponents;
                var detailAddress = "";
                if (addComp) {
                    if (addComp.province != addComp.city) {
                        detailAddress += addComp.province;
                    }
                    detailAddress = detailAddress + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                }
                var searchInfoWindow = new BMapLib.SearchInfoWindow(map, detailAddress, {
                    title: settings.SearchAddress, //标题
                    width: 290, //宽度
                    height: 40, //高度
                    panel: "panel", //查询结果面板
                    enableAutoPan: true, //自动平移
                    searchTypes: [
                    ]
                });
                searchInfoWindow.open(marker);
            });
        })
    }

    //添加点
    function addMarker(point) {
        var marker = new BMap.Marker(point);
        autoMarkers.push(marker);
        map.addOverlay(marker);
        bindInfoWindow(marker, point);
    }

    //标注点，并可拖动标注点
    function addDragalbeMarker(point) {
        //removeIMarker(map);
        iMarker = new BMap.Marker(point, { icon: new BMap.Icon(settings.IconPath, new BMap.Size(22, 24)) });
        //var label = new BMap.Label("我是可以拖动的", { offset: new BMap.Size(20, -10) });
        //marker.setLabel(label)
        map.addOverlay(iMarker);
        iMarker.enableDragging();
        iMarker.setTop(true);
        iMarker.addEventListener("dragend", function (e) {
            setGeoPoint(e.point);
        });
        setGeoPoint(point);
        bindInfoWindow(iMarker, point);
    }

    //得到标注点的坐标
    function setGeoPoint(point) {
        $("#" + settings.GeoContainer).val(point.lng + ", " + point.lat);
    }

    //清除所有的点
    function removeMarkers() {
        map.removeOverlay(autoMarkers);
        autoMarkers = [];
    }

    function removeIMarker() {
        map.removeOverlay(iMarker);
        iMarker = null;
    }
})(jQuery);